package com.TeaManage.servlet;

import com.TeaManage.bean.Tea;
import com.TeaManage.bean.TeaCategory;
import com.TeaManage.util.GokJDBCUtil;

import javax.servlet.annotation.MultipartConfig;
import javax.servlet.http.Part;
import java.io.File;
import java.util.ArrayList;
import java.util.List;


@javax.servlet.annotation.WebServlet(name = "TeaServlet", urlPatterns = "/TeaServlet")
@MultipartConfig(maxFileSize = 1024 * 1024 * 10) // 10MB
public class TeaServlet extends javax.servlet.http.HttpServlet {
    @Override
    protected void doPost(javax.servlet.http.HttpServletRequest request, javax.servlet.http.HttpServletResponse response) throws javax.servlet.ServletException, java.io.IOException {
        response.setContentType("text/html;charset=utf-8");
        request.setCharacterEncoding("utf-8");
        doGet(request, response);
    }

    @Override
    protected void doGet(javax.servlet.http.HttpServletRequest request, javax.servlet.http.HttpServletResponse response) throws javax.servlet.ServletException, java.io.IOException {
        response.setContentType("text/html;charset=utf-8");
        request.setCharacterEncoding("utf-8");
        String method = request.getParameter("action");
        if ("add".equals( method)){
            // 获取参数并验证
            String teaName = request.getParameter("tea_name");
            String description = request.getParameter("description");
            String priceStr = request.getParameter("price");
            String unit = request.getParameter("unit");
            String categoryIdStr = request.getParameter("tea_category_id");

            // 验证必填字段
            if (teaName == null || teaName.trim().isEmpty() ||
                    description == null || description.trim().isEmpty() ||
                    priceStr == null || priceStr.trim().isEmpty() ||
                    unit == null || unit.trim().isEmpty() ||
                    categoryIdStr == null || categoryIdStr.trim().isEmpty()) {

                request.setAttribute("error", "所有字段都必须填写");
                request.getRequestDispatcher("/views/tea/addTea.jsp").forward(request, response);
                return;
            }

            try {
                double price = Double.parseDouble(priceStr);
                int categoryId = Integer.parseInt(categoryIdStr);

                // 处理图片上传
                Part filePart = request.getPart("image");
                String fileName = null;

                if (filePart != null && filePart.getSize() > 0) {
                    fileName = getFileName(filePart);
                    String uploadPath = getServletContext().getRealPath("images/upload") ;
                    File uploadDir = new File(uploadPath);
                    if (!uploadDir.exists()) uploadDir.mkdir();
                    filePart.write(uploadPath + File.separator + fileName);
                }

                String sql = "INSERT INTO tea(tea_name, description, price, unit, tea_category_id, image) VALUES(?,?,?,?,?,?)";
                int count = GokJDBCUtil.update(sql, teaName, description, price, unit, categoryId, fileName);
                response.sendRedirect("TeaServlet");

            } catch (NumberFormatException e) {
                request.setAttribute("error", "价格或分类ID格式不正确");
                request.getRequestDispatcher("/views/tea/addTea.jsp").forward(request, response);
            }
        }else if ("toAdd".equals(method)){
            // 跳转到新增页面
            String categorySql = "SELECT * FROM tea_category";
            List<TeaCategory> categoryList = GokJDBCUtil.queryAll(categorySql, TeaCategory.class);
            request.setAttribute("categoryList", categoryList);
            request.getRequestDispatcher("/views/tea/addTea.jsp").forward(request, response);
        } else if ("deleteById".equals( method)){
            // 处理删除逻辑
            int id = Integer.parseInt(request.getParameter("id"));

            // 先获取图片路径以便删除图片文件
            Tea tea = GokJDBCUtil.queryForObject("SELECT * FROM tea WHERE tea_id = ?", Tea.class, id);
            if (tea != null && tea.getImage() != null) {
                String imagePath = getServletContext().getRealPath("") + File.separator + "images" + File.separator + tea.getImage();
                File imageFile = new File(imagePath);
                if (imageFile.exists()) {
                    imageFile.delete();
                }
            }

            String sql = "DELETE FROM tea WHERE tea_id = ?";
            int count = GokJDBCUtil.update(sql, id);
            response.sendRedirect("TeaServlet");
        }else if ("findById".equals( method)){
            int id = Integer.parseInt(request.getParameter("id"));
            String sql = "select * from tea where tea_id = ?";
            String sql2 = "select * from tea_category";
            List<TeaCategory> categories = GokJDBCUtil.queryAll(sql2, TeaCategory.class);
            request.setAttribute("categoryList", categories);
            Tea tea = GokJDBCUtil.queryForObject(sql, Tea.class, id);
//            System.out.println( tea);
            request.setAttribute("tea", tea);
            request.getRequestDispatcher("/views/tea/editTea.jsp").forward(request, response);
        }else if ("update".equals( method)){
            int id = Integer.parseInt(request.getParameter("tea_id"));
            String name = request.getParameter("tea_name");
            String description = request.getParameter("description");
            double price = Double.parseDouble(request.getParameter("price"));
            String unit = request.getParameter("unit");
            int category_id = Integer.parseInt(request.getParameter("tea_category_id"));

            // 获取原有茶叶信息
            Tea oldTea = GokJDBCUtil.queryForObject("SELECT * FROM tea WHERE tea_id = ?", Tea.class, id);
            String fileName = oldTea.getImage(); // 默认使用原有图片

            // 处理图片上传
            Part filePart = request.getPart("image");
            if (filePart != null && filePart.getSize() > 0) {
                // 删除旧图片
                if (oldTea.getImage() != null) {
                    String oldImagePath = getServletContext().getRealPath("") + File.separator + "images" + File.separator + oldTea.getImage();
                    File oldImageFile = new File(oldImagePath);
                    if (oldImageFile.exists()) {
                        oldImageFile.delete();
                    }
                }

                // 上传新图片
                fileName = getFileName(filePart);
                String uploadPath = getServletContext().getRealPath("") + File.separator + "images";
                File uploadDir = new File(uploadPath);
                if (!uploadDir.exists()) uploadDir.mkdir();
                filePart.write(uploadPath + File.separator + fileName);
            }

            String sql = "UPDATE tea SET tea_name = ?, description = ?, price = ?, unit = ?, tea_category_id = ?, image = ? WHERE tea_id = ?";
            int count = GokJDBCUtil.update(sql, name, description, price, unit, category_id, fileName, id);
            if (count > 0) {
                response.sendRedirect("TeaServlet");
            }
        }else if ("search".equals( method)){
            String name = request.getParameter("name");
            String categoryIdStr = request.getParameter("categoryId");
            // 分页
            int page = 1;
            int pageSize = 10;
            try {
                page = Integer.parseInt(request.getParameter("page"));
                pageSize = Integer.parseInt(request.getParameter("pageSize"));
            } catch (Exception e) {
                page = 1;
                pageSize = 10;
            }
            // 构建动态 SQL 和参数列表
            StringBuilder sql = new StringBuilder("SELECT * FROM tea WHERE 1=1");
            List<Object> params = new ArrayList<>();
            if (name != null && !name.trim().isEmpty()) {
                sql.append(" AND tea_name LIKE ?");
                params.add("%" + name + "%");
            }
            if (categoryIdStr != null && !categoryIdStr.trim().isEmpty()) {
                sql.append(" AND tea_category_id = ?");
                params.add(Integer.parseInt(categoryIdStr));
            }
            // 查询总数
            String countSql = "SELECT COUNT(*) FROM (" + sql.toString() + ") AS total";
            int total = GokJDBCUtil.queryForCount(countSql, params.toArray());
            // 添加分页
            sql.append(" LIMIT ?, ?");
            params.add((page - 1) * pageSize);
            params.add(pageSize);
            List<Tea> teaList = GokJDBCUtil.queryAll(sql.toString(), Tea.class, params.toArray());
            // 计算总页数
            int totalPages = total % pageSize == 0 ? total / pageSize : total / pageSize + 1;
            // 获取分类列表
            String categorySql = "SELECT * FROM tea_category";
            List<TeaCategory> categoryList = GokJDBCUtil.queryAll(categorySql, TeaCategory.class);
            // 返回结果
            request.setAttribute("teaList", teaList);
            request.setAttribute("categoryList", categoryList);
            request.setAttribute("name", name);
            request.setAttribute("categoryId", categoryIdStr);
            request.setAttribute("page", page);
            request.setAttribute("pageSize", pageSize);
            request.setAttribute("totalPages", totalPages);
            request.getRequestDispatcher("views/tea/tea.jsp").forward(request, response);
        }else{
            // 分页参数
            int page = 1;
            int pageSize = 5;
            try {
                page = Integer.parseInt(request.getParameter("page"));
                pageSize = Integer.parseInt(request.getParameter("pageSize"));
            } catch (Exception e) {
                page = 1;
                pageSize = 5;
            }
            // 查询总数
            String countSql = "SELECT COUNT(*) FROM tea";
            int total = GokJDBCUtil.queryForCount(countSql);
            // 查询数据
            String sql = "SELECT * FROM tea LIMIT ?, ?";
            List<Tea> teaList = GokJDBCUtil.queryAll(sql, Tea.class, (page-1)*pageSize, pageSize);
            int totalPages = total % pageSize == 0 ? total / pageSize : total / pageSize + 1;
            request.setAttribute("teaList", teaList);
            String sql2 = "select * from tea_category";
            List<TeaCategory> categoryList = GokJDBCUtil.queryAll(sql2, TeaCategory.class);
            request.setAttribute("categoryList", categoryList);
            request.setAttribute("page", page);
            request.setAttribute("pageSize", pageSize);
            request.setAttribute("totalPages", totalPages);
            request.getRequestDispatcher("views/tea/tea.jsp").forward(request, response);
        }
    }
    private String getFileName(final Part part) {
        final String partHeader = part.getHeader("content-disposition");
        for (String content : partHeader.split(";")) {
            if (content.trim().startsWith("filename")) {
                String fileName=content.substring(content.indexOf('=') + 1).trim().replace("\"", "");
                return fileName.substring(fileName.lastIndexOf(File.separator) + 1);
            }
        }
        return null;
    }
}